<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perltie - how to hide an object class in a simple variable - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perltie">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perltie.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perltie">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perltie">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perltie">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perltie">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perltie">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perltie">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perltie">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perltie">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perltie">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perltie">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perltie">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perltie">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perltie">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perltie">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perltie">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perltie">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perltie">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perltie">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perltie">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perltie">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perltie">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perltie">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perltie">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perltie">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perltie">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perltie">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perltie">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perltie">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perltie">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perltie">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perltie">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perltie">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perltie">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perltie">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perltie">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perltie">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perltie">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perltie">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perltie">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perltie">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perltie">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perltie">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perltie">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perltie">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perltie">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perltie">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perltie">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perltie">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perltie">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perltie">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perltie">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perltie">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perltie">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perltie">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perltie">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perltie">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perltie">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perltie">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perltie">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perltie">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perltie">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perltie">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perltie">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perltie">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perltie">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perltie">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perltie">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perltie">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perltie">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perltie">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perltie">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perltie">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perltie">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perltie">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perltie">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perltie">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perltie">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perltie">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perltie">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perltie">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perltie.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perltie">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perltie">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perltie">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perltie">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perltie">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perltie">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perltie">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perltie">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perltie">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perltie">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perltie">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perltie">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perltie">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perltie">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perltie">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perltie">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perltie">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perltie">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perltie">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perltie">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perltie">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perltie">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perltie">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perltie">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perltie">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perltie">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perltie">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perltie">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perltie">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perltie">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perltie">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perltie">5.35.1</a>
          <a class="dropdown-item active" href="perltie.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perltie.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perltie.html">perltie</a>
          <div id="more">
            (<a href="perltie.txt">source</a>,
            <a href="https://metacpan.org/pod/perltie">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perltie.html#NAME">NAME </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#SYNOPSIS">SYNOPSIS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#DESCRIPTION">DESCRIPTION</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perltie.html#Tying-Scalars">Tying Scalars </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#Tying-Arrays">Tying Arrays </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#Tying-Hashes">Tying Hashes </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#Tying-FileHandles">Tying FileHandles </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#UNTIE-this4">UNTIE this </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#The-untie-Gotcha">The untie Gotcha </a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#SEE-ALSO">SEE ALSO</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#BUGS">BUGS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perltie.html#AUTHOR">AUTHOR</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perltie.html#NAME">#</a>NAME </h1>

<p>perltie - how to hide an object class in a simple variable</p>

<h1 id="SYNOPSIS"><a class="permalink" href="perltie.html#SYNOPSIS">#</a>SYNOPSIS</h1>

<pre><code>tie VARIABLE, CLASSNAME, LIST

$object = tied VARIABLE

untie VARIABLE</code></pre>

<h1 id="DESCRIPTION"><a class="permalink" href="perltie.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>Prior to release 5.0 of Perl, a programmer could use dbmopen() to connect an on-disk database in the standard Unix dbm(3x) format magically to a %HASH in their program. However, their Perl was either built with one particular dbm library or another, but not both, and you couldn&#39;t extend this mechanism to other packages or types of variables.</p>

<p>Now you can.</p>

<p>The tie() function binds a variable to a class (package) that will provide the implementation for access methods for that variable. Once this magic has been performed, accessing a tied variable automatically triggers method calls in the proper class. The complexity of the class is hidden behind magic methods calls. The method names are in ALL CAPS, which is a convention that Perl uses to indicate that they&#39;re called implicitly rather than explicitly--just like the BEGIN() and END() functions.</p>

<p>In the tie() call, <code>VARIABLE</code> is the name of the variable to be enchanted. <code>CLASSNAME</code> is the name of a class implementing objects of the correct type. Any additional arguments in the <code>LIST</code> are passed to the appropriate constructor method for that class--meaning TIESCALAR(), TIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments such as might be passed to the dbminit() function of C.) The object returned by the &quot;new&quot; method is also returned by the tie() function, which would be useful if you wanted to access other methods in <code>CLASSNAME</code>. (You don&#39;t actually have to return a reference to a right &quot;type&quot; (e.g., HASH or <code>CLASSNAME</code>) so long as it&#39;s a properly blessed object.) You can also retrieve a reference to the underlying object using the tied() function.</p>

<p>Unlike dbmopen(), the tie() function will not <code>use</code> or <code>require</code> a module for you--you need to do that explicitly yourself.</p>

<h2 id="Tying-Scalars"><a class="permalink" href="perltie.html#Tying-Scalars">#</a><a id="Tying"></a>Tying Scalars </h2>

<p>A class implementing a tied scalar should define the following methods: TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.</p>

<p>Let&#39;s look at each in turn, using as an example a tie class for scalars that allows the user to do something like:</p>

<pre><code>tie $his_speed, &#39;Nice&#39;, getppid();
tie $my_speed,  &#39;Nice&#39;, $$;</code></pre>

<p>And now whenever either of those variables is accessed, its current system priority is retrieved and returned. If those variables are set, then the process&#39;s priority is changed!</p>

<p>We&#39;ll use Jarkko Hietaniemi &lt;<i>jhi@iki.fi</i>&gt;&#39;s BSD::Resource class (not included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants from your system, as well as the getpriority() and setpriority() system calls. Here&#39;s the preamble of the class.</p>

<pre><code>package Nice;
use Carp;
use BSD::Resource;
use strict;
$Nice::DEBUG = 0 unless defined $Nice::DEBUG;</code></pre>

<dl>

<dt id="TIESCALAR-classname,-LIST"><a class="permalink" href="perltie.html#TIESCALAR-classname,-LIST">#</a><a id="TIESCALAR"></a><a id="TIESCALAR-classname-LIST"></a>TIESCALAR classname, LIST </dt>
<dd>

<p>This is the constructor for the class. That means it is expected to return a blessed reference to a new scalar (probably anonymous) that it&#39;s creating. For example:</p>

<pre><code>sub TIESCALAR {
    my $class = shift;
    my $pid = shift || $$; # 0 means me

    if ($pid !~ /^\d+$/) {
        carp &quot;Nice::Tie::Scalar got non-numeric pid $pid&quot; if $^W;
        return undef;
    }

    unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
        carp &quot;Nice::Tie::Scalar got bad pid $pid: $!&quot; if $^W;
        return undef;
    }

    return bless \$pid, $class;
}</code></pre>

<p>This tie class has chosen to return an error rather than raising an exception if its constructor should fail. While this is how dbmopen() works, other classes may well not wish to be so forgiving. It checks the global variable <code>$^W</code> to see whether to emit a bit of noise anyway.</p>

</dd>
<dt id="FETCH-this"><a class="permalink" href="perltie.html#FETCH-this">#</a><a id="FETCH"></a>FETCH this </dt>
<dd>

<p>This method will be triggered every time the tied variable is accessed (read). It takes no arguments beyond its self reference, which is the object representing the scalar we&#39;re dealing with. Because in this case we&#39;re using just a SCALAR ref for the tied scalar object, a simple $$self allows the method to get at the real value stored there. In our example below, that real value is the process ID to which we&#39;ve tied our variable.</p>

<pre><code>sub FETCH {
    my $self = shift;
    confess &quot;wrong type&quot; unless ref $self;
    croak &quot;usage error&quot; if @_;
    my $nicety;
    local($!) = 0;
    $nicety = getpriority(PRIO_PROCESS, $$self);
    if ($!) { croak &quot;getpriority failed: $!&quot; }
    return $nicety;
}</code></pre>

<p>This time we&#39;ve decided to blow up (raise an exception) if the renice fails--there&#39;s no place for us to return an error otherwise, and it&#39;s probably the right thing to do.</p>

</dd>
<dt id="STORE-this,-value"><a class="permalink" href="perltie.html#STORE-this,-value">#</a><a id="STORE"></a><a id="STORE-this-value"></a>STORE this, value </dt>
<dd>

<p>This method will be triggered every time the tied variable is set (assigned). Beyond its self reference, it also expects one (and only one) argument: the new value the user is trying to assign. Don&#39;t worry about returning a value from STORE; the semantic of assignment returning the assigned value is implemented with FETCH.</p>

<pre><code>sub STORE {
    my $self = shift;
    confess &quot;wrong type&quot; unless ref $self;
    my $new_nicety = shift;
    croak &quot;usage error&quot; if @_;

    if ($new_nicety &lt; PRIO_MIN) {
        carp sprintf
          &quot;WARNING: priority %d less than minimum system priority %d&quot;,
              $new_nicety, PRIO_MIN if $^W;
        $new_nicety = PRIO_MIN;
    }

    if ($new_nicety &gt; PRIO_MAX) {
        carp sprintf
          &quot;WARNING: priority %d greater than maximum system priority %d&quot;,
              $new_nicety, PRIO_MAX if $^W;
        $new_nicety = PRIO_MAX;
    }

    unless (defined setpriority(PRIO_PROCESS,
                                $$self,
                                $new_nicety))
    {
        confess &quot;setpriority failed: $!&quot;;
    }
}</code></pre>

</dd>
<dt id="UNTIE-this"><a class="permalink" href="perltie.html#UNTIE-this">#</a><a id="UNTIE"></a>UNTIE this </dt>
<dd>

<p>This method will be triggered when the <code>untie</code> occurs. This can be useful if the class needs to know when no further calls will be made. (Except DESTROY of course.) See <a href="perltie.html#The-untie-Gotcha">&quot;The <code>untie</code> Gotcha&quot;</a> below for more details.</p>

</dd>
<dt id="DESTROY-this"><a class="permalink" href="perltie.html#DESTROY-this">#</a><a id="DESTROY"></a>DESTROY this </dt>
<dd>

<p>This method will be triggered when the tied variable needs to be destructed. As with other object classes, such a method is seldom necessary, because Perl deallocates its moribund object&#39;s memory for you automatically--this isn&#39;t C++, you know. We&#39;ll use a DESTROY method here for debugging purposes only.</p>

<pre><code>sub DESTROY {
    my $self = shift;
    confess &quot;wrong type&quot; unless ref $self;
    carp &quot;[ Nice::DESTROY pid $$self ]&quot; if $Nice::DEBUG;
}</code></pre>

</dd>
</dl>

<p>That&#39;s about all there is to it. Actually, it&#39;s more than all there is to it, because we&#39;ve done a few nice things here for the sake of completeness, robustness, and general aesthetics. Simpler TIESCALAR classes are certainly possible.</p>

<h2 id="Tying-Arrays"><a class="permalink" href="perltie.html#Tying-Arrays">#</a><a id="Tying1"></a>Tying Arrays </h2>

<p>A class implementing a tied ordinary array should define the following methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE, CLEAR and perhaps UNTIE and/or DESTROY.</p>

<p>FETCHSIZE and STORESIZE are used to provide <code>$#array</code> and equivalent <code>scalar(@array)</code> access.</p>

<p>The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are required if the perl operator with the corresponding (but lowercase) name is to operate on the tied array. The <b>Tie::Array</b> class can be used as a base class to implement the first five of these in terms of the basic methods above. The default implementations of DELETE and EXISTS in <b>Tie::Array</b> simply <code>croak</code>.</p>

<p>In addition EXTEND will be called when perl would have pre-extended allocation in a real array.</p>

<p>For this discussion, we&#39;ll implement an array whose elements are a fixed size at creation. If you try to create an element larger than the fixed size, you&#39;ll take an exception. For example:</p>

<pre><code>use FixedElem_Array;
tie @array, &#39;FixedElem_Array&#39;, 3;
$array[0] = &#39;cat&#39;;  # ok.
$array[1] = &#39;dogs&#39;; # exception, length(&#39;dogs&#39;) &gt; 3.</code></pre>

<p>The preamble code for the class is as follows:</p>

<pre><code>package FixedElem_Array;
use Carp;
use strict;</code></pre>

<dl>

<dt id="TIEARRAY-classname,-LIST"><a class="permalink" href="perltie.html#TIEARRAY-classname,-LIST">#</a><a id="TIEARRAY"></a><a id="TIEARRAY-classname-LIST"></a>TIEARRAY classname, LIST </dt>
<dd>

<p>This is the constructor for the class. That means it is expected to return a blessed reference through which the new array (probably an anonymous ARRAY ref) will be accessed.</p>

<p>In our example, just to show you that you don&#39;t <i>really</i> have to return an ARRAY reference, we&#39;ll choose a HASH reference to represent our object. A HASH works out well as a generic record type: the <code>{ELEMSIZE}</code> field will store the maximum element size allowed, and the <code>{ARRAY}</code> field will hold the true ARRAY ref. If someone outside the class tries to dereference the object returned (doubtless thinking it an ARRAY ref), they&#39;ll blow up. This just goes to show you that you should respect an object&#39;s privacy.</p>

<pre><code>sub TIEARRAY {
  my $class    = shift;
  my $elemsize = shift;
  if ( @_ || $elemsize =~ /\D/ ) {
    croak &quot;usage: tie ARRAY, &#39;&quot; . __PACKAGE__ . &quot;&#39;, elem_size&quot;;
  }
  return bless {
    ELEMSIZE =&gt; $elemsize,
    ARRAY    =&gt; [],
  }, $class;
}</code></pre>

</dd>
<dt id="FETCH-this,-index"><a class="permalink" href="perltie.html#FETCH-this,-index">#</a><a id="FETCH1"></a><a id="FETCH-this-index"></a>FETCH this, index </dt>
<dd>

<p>This method will be triggered every time an individual element the tied array is accessed (read). It takes one argument beyond its self reference: the index whose value we&#39;re trying to fetch.</p>

<pre><code>sub FETCH {
  my $self  = shift;
  my $index = shift;
  return $self-&gt;{ARRAY}-&gt;[$index];
}</code></pre>

<p>If a negative array index is used to read from an array, the index will be translated to a positive one internally by calling FETCHSIZE before being passed to FETCH. You may disable this feature by assigning a true value to the variable <code>$NEGATIVE_INDICES</code> in the tied array class.</p>

<p>As you may have noticed, the name of the FETCH method (et al.) is the same for all accesses, even though the constructors differ in names (TIESCALAR vs TIEARRAY). While in theory you could have the same class servicing several tied types, in practice this becomes cumbersome, and it&#39;s easiest to keep them at simply one tie type per class.</p>

</dd>
<dt id="STORE-this,-index,-value"><a class="permalink" href="perltie.html#STORE-this,-index,-value">#</a><a id="STORE1"></a><a id="STORE-this-index-value"></a>STORE this, index, value </dt>
<dd>

<p>This method will be triggered every time an element in the tied array is set (written). It takes two arguments beyond its self reference: the index at which we&#39;re trying to store something and the value we&#39;re trying to put there.</p>

<p>In our example, <code>undef</code> is really <code>$self-&gt;{ELEMSIZE}</code> number of spaces so we have a little more work to do here:</p>

<pre><code>sub STORE {
  my $self = shift;
  my( $index, $value ) = @_;
  if ( length $value &gt; $self-&gt;{ELEMSIZE} ) {
    croak &quot;length of $value is greater than $self-&gt;{ELEMSIZE}&quot;;
  }
  # fill in the blanks
  $self-&gt;STORESIZE( $index ) if $index &gt; $self-&gt;FETCHSIZE();
  # right justify to keep element size for smaller elements
  $self-&gt;{ARRAY}-&gt;[$index] = sprintf &quot;%$self-&gt;{ELEMSIZE}s&quot;, $value;
}</code></pre>

<p>Negative indexes are treated the same as with FETCH.</p>

</dd>
<dt id="FETCHSIZE-this"><a class="permalink" href="perltie.html#FETCHSIZE-this">#</a><a id="FETCHSIZE"></a>FETCHSIZE this </dt>
<dd>

<p>Returns the total number of items in the tied array associated with object <i>this</i>. (Equivalent to <code>scalar(@array)</code>). For example:</p>

<pre><code>sub FETCHSIZE {
  my $self = shift;
  return scalar $self-&gt;{ARRAY}-&gt;@*;
}</code></pre>

</dd>
<dt id="STORESIZE-this,-count"><a class="permalink" href="perltie.html#STORESIZE-this,-count">#</a><a id="STORESIZE"></a><a id="STORESIZE-this-count"></a>STORESIZE this, count </dt>
<dd>

<p>Sets the total number of items in the tied array associated with object <i>this</i> to be <i>count</i>. If this makes the array larger then class&#39;s mapping of <code>undef</code> should be returned for new positions. If the array becomes smaller then entries beyond count should be deleted.</p>

<p>In our example, &#39;undef&#39; is really an element containing <code>$self-&gt;{ELEMSIZE}</code> number of spaces. Observe:</p>

<pre><code>sub STORESIZE {
  my $self  = shift;
  my $count = shift;
  if ( $count &gt; $self-&gt;FETCHSIZE() ) {
    foreach ( $count - $self-&gt;FETCHSIZE() .. $count ) {
      $self-&gt;STORE( $_, &#39;&#39; );
    }
  } elsif ( $count &lt; $self-&gt;FETCHSIZE() ) {
    foreach ( 0 .. $self-&gt;FETCHSIZE() - $count - 2 ) {
      $self-&gt;POP();
    }
  }
}</code></pre>

</dd>
<dt id="EXTEND-this,-count"><a class="permalink" href="perltie.html#EXTEND-this,-count">#</a><a id="EXTEND"></a><a id="EXTEND-this-count"></a>EXTEND this, count </dt>
<dd>

<p>Informative call that array is likely to grow to have <i>count</i> entries. Can be used to optimize allocation. This method need do nothing.</p>

<p>In our example there is no reason to implement this method, so we leave it as a no-op. This method is only relevant to tied array implementations where there is the possibility of having the allocated size of the array be larger than is visible to a perl programmer inspecting the size of the array. Many tied array implementations will have no reason to implement it.</p>

<pre><code>sub EXTEND {   
  my $self  = shift;
  my $count = shift;
  # nothing to see here, move along.
}</code></pre>

<p><b>NOTE:</b> It is generally an error to make this equivalent to STORESIZE. Perl may from time to time call EXTEND without wanting to actually change the array size directly. Any tied array should function correctly if this method is a no-op, even if perhaps they might not be as efficient as they would if this method was implemented.</p>

</dd>
<dt id="EXISTS-this,-key"><a class="permalink" href="perltie.html#EXISTS-this,-key">#</a><a id="EXISTS"></a><a id="EXISTS-this-key"></a>EXISTS this, key </dt>
<dd>

<p>Verify that the element at index <i>key</i> exists in the tied array <i>this</i>.</p>

<p>In our example, we will determine that if an element consists of <code>$self-&gt;{ELEMSIZE}</code> spaces only, it does not exist:</p>

<pre><code>sub EXISTS {
  my $self  = shift;
  my $index = shift;
  return 0 if ! defined $self-&gt;{ARRAY}-&gt;[$index] ||
              $self-&gt;{ARRAY}-&gt;[$index] eq &#39; &#39; x $self-&gt;{ELEMSIZE};
  return 1;
}</code></pre>

</dd>
<dt id="DELETE-this,-key"><a class="permalink" href="perltie.html#DELETE-this,-key">#</a><a id="DELETE"></a><a id="DELETE-this-key"></a>DELETE this, key </dt>
<dd>

<p>Delete the element at index <i>key</i> from the tied array <i>this</i>.</p>

<p>In our example, a deleted item is <code>$self-&gt;{ELEMSIZE}</code> spaces:</p>

<pre><code>sub DELETE {
  my $self  = shift;
  my $index = shift;
  return $self-&gt;STORE( $index, &#39;&#39; );
}</code></pre>

</dd>
<dt id="CLEAR-this"><a class="permalink" href="perltie.html#CLEAR-this">#</a><a id="CLEAR"></a>CLEAR this </dt>
<dd>

<p>Clear (remove, delete, ...) all values from the tied array associated with object <i>this</i>. For example:</p>

<pre><code>sub CLEAR {
  my $self = shift;
  return $self-&gt;{ARRAY} = [];
}</code></pre>

</dd>
<dt id="PUSH-this,-LIST"><a class="permalink" href="perltie.html#PUSH-this,-LIST">#</a><a id="PUSH"></a><a id="PUSH-this-LIST"></a>PUSH this, LIST </dt>
<dd>

<p>Append elements of <i>LIST</i> to the array. For example:</p>

<pre><code>sub PUSH {  
  my $self = shift;
  my @list = @_;
  my $last = $self-&gt;FETCHSIZE();
  $self-&gt;STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
  return $self-&gt;FETCHSIZE();
}   </code></pre>

</dd>
<dt id="POP-this"><a class="permalink" href="perltie.html#POP-this">#</a><a id="POP"></a>POP this </dt>
<dd>

<p>Remove last element of the array and return it. For example:</p>

<pre><code>sub POP {
  my $self = shift;
  return pop $self-&gt;{ARRAY}-&gt;@*;
}</code></pre>

</dd>
<dt id="SHIFT-this"><a class="permalink" href="perltie.html#SHIFT-this">#</a><a id="SHIFT"></a>SHIFT this </dt>
<dd>

<p>Remove the first element of the array (shifting other elements down) and return it. For example:</p>

<pre><code>sub SHIFT {
  my $self = shift;
  return shift $self-&gt;{ARRAY}-&gt;@*;
}</code></pre>

</dd>
<dt id="UNSHIFT-this,-LIST"><a class="permalink" href="perltie.html#UNSHIFT-this,-LIST">#</a><a id="UNSHIFT"></a><a id="UNSHIFT-this-LIST"></a>UNSHIFT this, LIST </dt>
<dd>

<p>Insert LIST elements at the beginning of the array, moving existing elements up to make room. For example:</p>

<pre><code>sub UNSHIFT {
  my $self = shift;
  my @list = @_;
  my $size = scalar( @list );
  # make room for our list
  $self-&gt;{ARRAY}[ $size .. $self-&gt;{ARRAY}-&gt;$#* + $size ]-&gt;@*
   = $self-&gt;{ARRAY}-&gt;@*
  $self-&gt;STORE( $_, $list[$_] ) foreach 0 .. $#list;
}</code></pre>

</dd>
<dt id="SPLICE-this,-offset,-length,-LIST"><a class="permalink" href="perltie.html#SPLICE-this,-offset,-length,-LIST">#</a><a id="SPLICE"></a><a id="SPLICE-this-offset-length-LIST"></a>SPLICE this, offset, length, LIST </dt>
<dd>

<p>Perform the equivalent of <code>splice</code> on the array.</p>

<p><i>offset</i> is optional and defaults to zero, negative values count back from the end of the array.</p>

<p><i>length</i> is optional and defaults to rest of the array.</p>

<p><i>LIST</i> may be empty.</p>

<p>Returns a list of the original <i>length</i> elements at <i>offset</i>.</p>

<p>In our example, we&#39;ll use a little shortcut if there is a <i>LIST</i>:</p>

<pre><code>sub SPLICE {
  my $self   = shift;
  my $offset = shift || 0;
  my $length = shift || $self-&gt;FETCHSIZE() - $offset;
  my @list   = (); 
  if ( @_ ) {
    tie @list, __PACKAGE__, $self-&gt;{ELEMSIZE};
    @list   = @_;
  }
  return splice $self-&gt;{ARRAY}-&gt;@*, $offset, $length, @list;
}</code></pre>

</dd>
<dt id="UNTIE-this1"><a class="permalink" href="perltie.html#UNTIE-this1">#</a><a id="UNTIE1"></a>UNTIE this </dt>
<dd>

<p>Will be called when <code>untie</code> happens. (See <a href="perltie.html#The-untie-Gotcha">&quot;The <code>untie</code> Gotcha&quot;</a> below.)</p>

</dd>
<dt id="DESTROY-this1"><a class="permalink" href="perltie.html#DESTROY-this1">#</a><a id="DESTROY1"></a>DESTROY this </dt>
<dd>

<p>This method will be triggered when the tied variable needs to be destructed. As with the scalar tie class, this is almost never needed in a language that does its own garbage collection, so this time we&#39;ll just leave it out.</p>

</dd>
</dl>

<h2 id="Tying-Hashes"><a class="permalink" href="perltie.html#Tying-Hashes">#</a><a id="Tying2"></a>Tying Hashes </h2>

<p>Hashes were the first Perl data type to be tied (see dbmopen()). A class implementing a tied hash should define the following methods: TIEHASH is the constructor. FETCH and STORE access the key and value pairs. EXISTS reports whether a key is present in the hash, and DELETE deletes one. CLEAR empties the hash by deleting all the key and value pairs. FIRSTKEY and NEXTKEY implement the keys() and each() functions to iterate over all the keys. SCALAR is triggered when the tied hash is evaluated in scalar context, and in 5.28 onwards, by <code>keys</code> in boolean context. UNTIE is called when <code>untie</code> happens, and DESTROY is called when the tied variable is garbage collected.</p>

<p>If this seems like a lot, then feel free to inherit from merely the standard Tie::StdHash module for most of your methods, redefining only the interesting ones. See <a href="./Tie::Hash.html">Tie::Hash</a> for details.</p>

<p>Remember that Perl distinguishes between a key not existing in the hash, and the key existing in the hash but having a corresponding value of <code>undef</code>. The two possibilities can be tested with the <code>exists()</code> and <code>defined()</code> functions.</p>

<p>Here&#39;s an example of a somewhat interesting tied hash class: it gives you a hash representing a particular user&#39;s dot files. You index into the hash with the name of the file (minus the dot) and you get back that dot file&#39;s contents. For example:</p>

<pre><code>    use DotFiles;
    tie %dot, &#39;DotFiles&#39;;
    if ( $dot{profile} =~ /MANPATH/ ||
         $dot{login}   =~ /MANPATH/ ||
         $dot{cshrc}   =~ /MANPATH/    )
    {
	print &quot;you seem to set your MANPATH\n&quot;;
    }</code></pre>

<p>Or here&#39;s another sample of using our tied class:</p>

<pre><code>    tie %him, &#39;DotFiles&#39;, &#39;daemon&#39;;
    foreach $f ( keys %him ) {
	printf &quot;daemon dot file %s is size %d\n&quot;,
	    $f, length $him{$f};
    }</code></pre>

<p>In our tied hash DotFiles example, we use a regular hash for the object containing several important fields, of which only the <code>{LIST}</code> field will be what the user thinks of as the real hash.</p>

<dl>

<dt id="USER"><a class="permalink" href="perltie.html#USER">#</a>USER</dt>
<dd>

<p>whose dot files this object represents</p>

</dd>
<dt id="HOME"><a class="permalink" href="perltie.html#HOME">#</a>HOME</dt>
<dd>

<p>where those dot files live</p>

</dd>
<dt id="CLOBBER"><a class="permalink" href="perltie.html#CLOBBER">#</a>CLOBBER</dt>
<dd>

<p>whether we should try to change or remove those dot files</p>

</dd>
<dt id="LIST"><a class="permalink" href="perltie.html#LIST">#</a>LIST</dt>
<dd>

<p>the hash of dot file names and content mappings</p>

</dd>
</dl>

<p>Here&#39;s the start of <i>Dotfiles.pm</i>:</p>

<pre><code>package DotFiles;
use Carp;
sub whowasi { (caller(1))[3] . &#39;()&#39; }
my $DEBUG = 0;
sub debug { $DEBUG = @_ ? shift : 1 }</code></pre>

<p>For our example, we want to be able to emit debugging info to help in tracing during development. We keep also one convenience function around internally to help print out warnings; whowasi() returns the function name that calls it.</p>

<p>Here are the methods for the DotFiles tied hash.</p>

<dl>

<dt id="TIEHASH-classname,-LIST"><a class="permalink" href="perltie.html#TIEHASH-classname,-LIST">#</a><a id="TIEHASH"></a><a id="TIEHASH-classname-LIST"></a>TIEHASH classname, LIST </dt>
<dd>

<p>This is the constructor for the class. That means it is expected to return a blessed reference through which the new object (probably but not necessarily an anonymous hash) will be accessed.</p>

<p>Here&#39;s the constructor:</p>

<pre><code>    sub TIEHASH {
	my $self = shift;
	my $user = shift || $&gt;;
	my $dotdir = shift || &#39;&#39;;
	croak &quot;usage: @{[&amp;whowasi]} [USER [DOTDIR]]&quot; if @_;
	$user = getpwuid($user) if $user =~ /^\d+$/;
	my $dir = (getpwnam($user))[7]
		|| croak &quot;@{[&amp;whowasi]}: no user $user&quot;;
	$dir .= &quot;/$dotdir&quot; if $dotdir;

	my $node = {
	    USER    =&gt; $user,
	    HOME    =&gt; $dir,
	    LIST    =&gt; {},
	    CLOBBER =&gt; 0,
	};

	opendir(DIR, $dir)
		|| croak &quot;@{[&amp;whowasi]}: can&#39;t opendir $dir: $!&quot;;
	foreach $dot ( grep /^\./ &amp;&amp; -f &quot;$dir/$_&quot;, readdir(DIR)) {
	    $dot =~ s/^\.//;
	    $node-&gt;{LIST}{$dot} = undef;
	}
	closedir DIR;
	return bless $node, $self;
    }</code></pre>

<p>It&#39;s probably worth mentioning that if you&#39;re going to filetest the return values out of a readdir, you&#39;d better prepend the directory in question. Otherwise, because we didn&#39;t chdir() there, it would have been testing the wrong file.</p>

</dd>
<dt id="FETCH-this,-key"><a class="permalink" href="perltie.html#FETCH-this,-key">#</a><a id="FETCH2"></a><a id="FETCH-this-key"></a>FETCH this, key </dt>
<dd>

<p>This method will be triggered every time an element in the tied hash is accessed (read). It takes one argument beyond its self reference: the key whose value we&#39;re trying to fetch.</p>

<p>Here&#39;s the fetch for our DotFiles example.</p>

<pre><code>    sub FETCH {
	carp &amp;whowasi if $DEBUG;
	my $self = shift;
	my $dot = shift;
	my $dir = $self-&gt;{HOME};
	my $file = &quot;$dir/.$dot&quot;;

	unless (exists $self-&gt;{LIST}-&gt;{$dot} || -f $file) {
	    carp &quot;@{[&amp;whowasi]}: no $dot file&quot; if $DEBUG;
	    return undef;
	}

	if (defined $self-&gt;{LIST}-&gt;{$dot}) {
	    return $self-&gt;{LIST}-&gt;{$dot};
	} else {
	    return $self-&gt;{LIST}-&gt;{$dot} = `cat $dir/.$dot`;
	}
    }</code></pre>

<p>It was easy to write by having it call the Unix cat(1) command, but it would probably be more portable to open the file manually (and somewhat more efficient). Of course, because dot files are a Unixy concept, we&#39;re not that concerned.</p>

</dd>
<dt id="STORE-this,-key,-value"><a class="permalink" href="perltie.html#STORE-this,-key,-value">#</a><a id="STORE2"></a><a id="STORE-this-key-value"></a>STORE this, key, value </dt>
<dd>

<p>This method will be triggered every time an element in the tied hash is set (written). It takes two arguments beyond its self reference: the index at which we&#39;re trying to store something, and the value we&#39;re trying to put there.</p>

<p>Here in our DotFiles example, we&#39;ll be careful not to let them try to overwrite the file unless they&#39;ve called the clobber() method on the original object reference returned by tie().</p>

<pre><code>    sub STORE {
	carp &amp;whowasi if $DEBUG;
	my $self = shift;
	my $dot = shift;
	my $value = shift;
	my $file = $self-&gt;{HOME} . &quot;/.$dot&quot;;
	my $user = $self-&gt;{USER};

	croak &quot;@{[&amp;whowasi]}: $file not clobberable&quot;
	    unless $self-&gt;{CLOBBER};

	open(my $f, &#39;&gt;&#39;, $file) || croak &quot;can&#39;t open $file: $!&quot;;
	print $f $value;
	close($f);
    }</code></pre>

<p>If they wanted to clobber something, they might say:</p>

<pre><code>$ob = tie %daemon_dots, &#39;daemon&#39;;
$ob-&gt;clobber(1);
$daemon_dots{signature} = &quot;A true daemon\n&quot;;</code></pre>

<p>Another way to lay hands on a reference to the underlying object is to use the tied() function, so they might alternately have set clobber using:</p>

<pre><code>tie %daemon_dots, &#39;daemon&#39;;
tied(%daemon_dots)-&gt;clobber(1);</code></pre>

<p>The clobber method is simply:</p>

<pre><code>    sub clobber {
	my $self = shift;
	$self-&gt;{CLOBBER} = @_ ? shift : 1;
    }</code></pre>

</dd>
<dt id="DELETE-this,-key1"><a class="permalink" href="perltie.html#DELETE-this,-key1">#</a><a id="DELETE1"></a><a id="DELETE-this-key1"></a>DELETE this, key </dt>
<dd>

<p>This method is triggered when we remove an element from the hash, typically by using the delete() function. Again, we&#39;ll be careful to check whether they really want to clobber files.</p>

<pre><code>sub DELETE   {
    carp &amp;whowasi if $DEBUG;

    my $self = shift;
    my $dot = shift;
    my $file = $self-&gt;{HOME} . &quot;/.$dot&quot;;
    croak &quot;@{[&amp;whowasi]}: won&#39;t remove file $file&quot;
        unless $self-&gt;{CLOBBER};
    delete $self-&gt;{LIST}-&gt;{$dot};
    my $success = unlink($file);
    carp &quot;@{[&amp;whowasi]}: can&#39;t unlink $file: $!&quot; unless $success;
    $success;
}</code></pre>

<p>The value returned by DELETE becomes the return value of the call to delete(). If you want to emulate the normal behavior of delete(), you should return whatever FETCH would have returned for this key. In this example, we have chosen instead to return a value which tells the caller whether the file was successfully deleted.</p>

</dd>
<dt id="CLEAR-this1"><a class="permalink" href="perltie.html#CLEAR-this1">#</a><a id="CLEAR1"></a>CLEAR this </dt>
<dd>

<p>This method is triggered when the whole hash is to be cleared, usually by assigning the empty list to it.</p>

<p>In our example, that would remove all the user&#39;s dot files! It&#39;s such a dangerous thing that they&#39;ll have to set CLOBBER to something higher than 1 to make it happen.</p>

<pre><code>sub CLEAR    {
    carp &amp;whowasi if $DEBUG;
    my $self = shift;
    croak &quot;@{[&amp;whowasi]}: won&#39;t remove all dot files for $self-&gt;{USER}&quot;
        unless $self-&gt;{CLOBBER} &gt; 1;
    my $dot;
    foreach $dot ( keys $self-&gt;{LIST}-&gt;%* ) {
        $self-&gt;DELETE($dot);
    }
}</code></pre>

</dd>
<dt id="EXISTS-this,-key1"><a class="permalink" href="perltie.html#EXISTS-this,-key1">#</a><a id="EXISTS1"></a><a id="EXISTS-this-key1"></a>EXISTS this, key </dt>
<dd>

<p>This method is triggered when the user uses the exists() function on a particular hash. In our example, we&#39;ll look at the <code>{LIST}</code> hash element for this:</p>

<pre><code>    sub EXISTS   {
	carp &amp;whowasi if $DEBUG;
	my $self = shift;
	my $dot = shift;
	return exists $self-&gt;{LIST}-&gt;{$dot};
    }</code></pre>

</dd>
<dt id="FIRSTKEY-this"><a class="permalink" href="perltie.html#FIRSTKEY-this">#</a><a id="FIRSTKEY"></a>FIRSTKEY this </dt>
<dd>

<p>This method will be triggered when the user is going to iterate through the hash, such as via a keys(), values(), or each() call.</p>

<pre><code>    sub FIRSTKEY {
	carp &amp;whowasi if $DEBUG;
	my $self = shift;
	my $a = keys $self-&gt;{LIST}-&gt;%*;  # reset each() iterator
	each $self-&gt;{LIST}-&gt;%*
    }</code></pre>

<p>FIRSTKEY is always called in scalar context and it should just return the first key. values(), and each() in list context, will call FETCH for the returned keys.</p>

</dd>
<dt id="NEXTKEY-this,-lastkey"><a class="permalink" href="perltie.html#NEXTKEY-this,-lastkey">#</a><a id="NEXTKEY"></a><a id="NEXTKEY-this-lastkey"></a>NEXTKEY this, lastkey </dt>
<dd>

<p>This method gets triggered during a keys(), values(), or each() iteration. It has a second argument which is the last key that had been accessed. This is useful if you&#39;re caring about ordering or calling the iterator from more than one sequence, or not really storing things in a hash anywhere.</p>

<p>NEXTKEY is always called in scalar context and it should just return the next key. values(), and each() in list context, will call FETCH for the returned keys.</p>

<p>For our example, we&#39;re using a real hash so we&#39;ll do just the simple thing, but we&#39;ll have to go through the LIST field indirectly.</p>

<pre><code>    sub NEXTKEY  {
	carp &amp;whowasi if $DEBUG;
	my $self = shift;
	return each $self-&gt;{LIST}-&gt;%*
    }</code></pre>

<p>If the object underlying your tied hash isn&#39;t a real hash and you don&#39;t have <code>each</code> available, then you should return <code>undef</code> or the empty list once you&#39;ve reached the end of your list of keys. See <a href="perlfunc.html#each"><code>each&#39;s own documentation</code></a> for more details.</p>

</dd>
<dt id="SCALAR-this"><a class="permalink" href="perltie.html#SCALAR-this">#</a><a id="SCALAR"></a>SCALAR this </dt>
<dd>

<p>This is called when the hash is evaluated in scalar context, and in 5.28 onwards, by <code>keys</code> in boolean context. In order to mimic the behaviour of untied hashes, this method must return a value which when used as boolean, indicates whether the tied hash is considered empty. If this method does not exist, perl will make some educated guesses and return true when the hash is inside an iteration. If this isn&#39;t the case, FIRSTKEY is called, and the result will be a false value if FIRSTKEY returns the empty list, true otherwise.</p>

<p>However, you should <b>not</b> blindly rely on perl always doing the right thing. Particularly, perl will mistakenly return true when you clear the hash by repeatedly calling DELETE until it is empty. You are therefore advised to supply your own SCALAR method when you want to be absolutely sure that your hash behaves nicely in scalar context.</p>

<p>In our example we can just call <code>scalar</code> on the underlying hash referenced by <code>$self-&gt;{LIST}</code>:</p>

<pre><code>    sub SCALAR {
	carp &amp;whowasi if $DEBUG;
	my $self = shift;
	return scalar $self-&gt;{LIST}-&gt;%*
    }</code></pre>

<p>NOTE: In perl 5.25 the behavior of scalar %hash on an untied hash changed to return the count of keys. Prior to this it returned a string containing information about the bucket setup of the hash. See <a href="./Hash::Util.html#bucket_ratio">&quot;bucket_ratio&quot; in Hash::Util</a> for a backwards compatibility path.</p>

</dd>
<dt id="UNTIE-this2"><a class="permalink" href="perltie.html#UNTIE-this2">#</a><a id="UNTIE2"></a>UNTIE this </dt>
<dd>

<p>This is called when <code>untie</code> occurs. See <a href="perltie.html#The-untie-Gotcha">&quot;The <code>untie</code> Gotcha&quot;</a> below.</p>

</dd>
<dt id="DESTROY-this2"><a class="permalink" href="perltie.html#DESTROY-this2">#</a><a id="DESTROY2"></a>DESTROY this </dt>
<dd>

<p>This method is triggered when a tied hash is about to go out of scope. You don&#39;t really need it unless you&#39;re trying to add debugging or have auxiliary state to clean up. Here&#39;s a very simple function:</p>

<pre><code>    sub DESTROY  {
	carp &amp;whowasi if $DEBUG;
    }</code></pre>

</dd>
</dl>

<p>Note that functions such as keys() and values() may return huge lists when used on large objects, like DBM files. You may prefer to use the each() function to iterate over such. Example:</p>

<pre><code># print out history file offsets
use NDBM_File;
tie(%HIST, &#39;NDBM_File&#39;, &#39;/usr/lib/news/history&#39;, 1, 0);
while (($key,$val) = each %HIST) {
    print $key, &#39; = &#39;, unpack(&#39;L&#39;,$val), &quot;\n&quot;;
}
untie(%HIST);</code></pre>

<h2 id="Tying-FileHandles"><a class="permalink" href="perltie.html#Tying-FileHandles">#</a><a id="Tying3"></a>Tying FileHandles </h2>

<p>This is partially implemented now.</p>

<p>A class implementing a tied filehandle should define the following methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC, READ, and possibly CLOSE, UNTIE and DESTROY. The class can also provide: BINMODE, OPEN, EOF, FILENO, SEEK, TELL - if the corresponding perl operators are used on the handle.</p>

<p>When STDERR is tied, its PRINT method will be called to issue warnings and error messages. This feature is temporarily disabled during the call, which means you can use <code>warn()</code> inside PRINT without starting a recursive loop. And just like <code>__WARN__</code> and <code>__DIE__</code> handlers, STDERR&#39;s PRINT method may be called to report parser errors, so the caveats mentioned under <a href="perlvar.html#%25SIG">&quot;%SIG&quot; in perlvar</a> apply.</p>

<p>All of this is especially useful when perl is embedded in some other program, where output to STDOUT and STDERR may have to be redirected in some special way. See nvi and the Apache module for examples.</p>

<p>When tying a handle, the first argument to <code>tie</code> should begin with an asterisk. So, if you are tying STDOUT, use <code>*STDOUT</code>. If you have assigned it to a scalar variable, say <code>$handle</code>, use <code>*$handle</code>. <code>tie $handle</code> ties the scalar variable <code>$handle</code>, not the handle inside it.</p>

<p>In our example we&#39;re going to create a shouting handle.</p>

<pre><code>package Shout;</code></pre>

<dl>

<dt id="TIEHANDLE-classname,-LIST"><a class="permalink" href="perltie.html#TIEHANDLE-classname,-LIST">#</a><a id="TIEHANDLE"></a><a id="TIEHANDLE-classname-LIST"></a>TIEHANDLE classname, LIST </dt>
<dd>

<p>This is the constructor for the class. That means it is expected to return a blessed reference of some sort. The reference can be used to hold some internal information.</p>

<pre><code>sub TIEHANDLE { print &quot;&lt;shout&gt;\n&quot;; my $i; bless \$i, shift }</code></pre>

</dd>
<dt id="WRITE-this,-LIST"><a class="permalink" href="perltie.html#WRITE-this,-LIST">#</a><a id="WRITE"></a><a id="WRITE-this-LIST"></a>WRITE this, LIST </dt>
<dd>

<p>This method will be called when the handle is written to via the <code>syswrite</code> function.</p>

<pre><code>sub WRITE {
    $r = shift;
    my($buf,$len,$offset) = @_;
    print &quot;WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset&quot;;
}</code></pre>

</dd>
<dt id="PRINT-this,-LIST"><a class="permalink" href="perltie.html#PRINT-this,-LIST">#</a><a id="PRINT"></a><a id="PRINT-this-LIST"></a>PRINT this, LIST </dt>
<dd>

<p>This method will be triggered every time the tied handle is printed to with the <code>print()</code> or <code>say()</code> functions. Beyond its self reference it also expects the list that was passed to the print function.</p>

<pre><code>sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }</code></pre>

<p><code>say()</code> acts just like <code>print()</code> except $\ will be localized to <code>\n</code> so you need do nothing special to handle <code>say()</code> in <code>PRINT()</code>.</p>

</dd>
<dt id="PRINTF-this,-LIST"><a class="permalink" href="perltie.html#PRINTF-this,-LIST">#</a><a id="PRINTF"></a><a id="PRINTF-this-LIST"></a>PRINTF this, LIST </dt>
<dd>

<p>This method will be triggered every time the tied handle is printed to with the <code>printf()</code> function. Beyond its self reference it also expects the format and list that was passed to the printf function.</p>

<pre><code>sub PRINTF {
    shift;
    my $fmt = shift;
    print sprintf($fmt, @_);
}</code></pre>

</dd>
<dt id="READ-this,-LIST"><a class="permalink" href="perltie.html#READ-this,-LIST">#</a><a id="READ"></a><a id="READ-this-LIST"></a>READ this, LIST </dt>
<dd>

<p>This method will be called when the handle is read from via the <code>read</code> or <code>sysread</code> functions.</p>

<pre><code>sub READ {
  my $self = shift;
  my $bufref = \$_[0];
  my(undef,$len,$offset) = @_;
  print &quot;READ called, \$buf=$bufref, \$len=$len, \$offset=$offset&quot;;
  # add to $$bufref, set $len to number of characters read
  $len;
}</code></pre>

</dd>
<dt id="READLINE-this"><a class="permalink" href="perltie.html#READLINE-this">#</a><a id="READLINE"></a>READLINE this </dt>
<dd>

<p>This method is called when the handle is read via <code>&lt;HANDLE&gt;</code> or <code>readline HANDLE</code>.</p>

<p>As per <a href="perlfunc.html#readline"><code>readline</code></a>, in scalar context it should return the next line, or <code>undef</code> for no more data. In list context it should return all remaining lines, or an empty list for no more data. The strings returned should include the input record separator <code>$/</code> (see <a href="perlvar.html">perlvar</a>), unless it is <code>undef</code> (which means &quot;slurp&quot; mode).</p>

<pre><code>sub READLINE {
  my $r = shift;
  if (wantarray) {
    return (&quot;all remaining\n&quot;,
            &quot;lines up\n&quot;,
            &quot;to eof\n&quot;);
  } else {
    return &quot;READLINE called &quot; . ++$$r . &quot; times\n&quot;;
  }
}</code></pre>

</dd>
<dt id="GETC-this"><a class="permalink" href="perltie.html#GETC-this">#</a><a id="GETC"></a>GETC this </dt>
<dd>

<p>This method will be called when the <code>getc</code> function is called.</p>

<pre><code class="plaintext">sub GETC { print &quot;Don&#39;t GETC, Get Perl&quot;; return &quot;a&quot;; }</code></pre>

</dd>
<dt id="EOF-this"><a class="permalink" href="perltie.html#EOF-this">#</a><a id="EOF"></a>EOF this </dt>
<dd>

<p>This method will be called when the <code>eof</code> function is called.</p>

<p>Starting with Perl 5.12, an additional integer parameter will be passed. It will be zero if <code>eof</code> is called without parameter; <code>1</code> if <code>eof</code> is given a filehandle as a parameter, e.g. <code>eof(FH)</code>; and <code>2</code> in the very special case that the tied filehandle is <code>ARGV</code> and <code>eof</code> is called with an empty parameter list, e.g. <code>eof()</code>.</p>

<pre><code>sub EOF { not length $stringbuf }</code></pre>

</dd>
<dt id="CLOSE-this"><a class="permalink" href="perltie.html#CLOSE-this">#</a><a id="CLOSE"></a>CLOSE this </dt>
<dd>

<p>This method will be called when the handle is closed via the <code>close</code> function.</p>

<pre><code class="plaintext">sub CLOSE { print &quot;CLOSE called.\n&quot; }</code></pre>

</dd>
<dt id="UNTIE-this3"><a class="permalink" href="perltie.html#UNTIE-this3">#</a><a id="UNTIE3"></a>UNTIE this </dt>
<dd>

<p>As with the other types of ties, this method will be called when <code>untie</code> happens. It may be appropriate to &quot;auto CLOSE&quot; when this occurs. See <a href="perltie.html#The-untie-Gotcha">&quot;The <code>untie</code> Gotcha&quot;</a> below.</p>

</dd>
<dt id="DESTROY-this3"><a class="permalink" href="perltie.html#DESTROY-this3">#</a><a id="DESTROY3"></a>DESTROY this </dt>
<dd>

<p>As with the other types of ties, this method will be called when the tied handle is about to be destroyed. This is useful for debugging and possibly cleaning up.</p>

<pre><code class="plaintext">sub DESTROY { print &quot;&lt;/shout&gt;\n&quot; }</code></pre>

</dd>
</dl>

<p>Here&#39;s how to use our little example:</p>

<pre><code>tie(*FOO,&#39;Shout&#39;);
print FOO &quot;hello\n&quot;;
$a = 4; $b = 6;
print FOO $a, &quot; plus &quot;, $b, &quot; equals &quot;, $a + $b, &quot;\n&quot;;
print &lt;FOO&gt;;</code></pre>

<h2 id="UNTIE-this4"><a class="permalink" href="perltie.html#UNTIE-this4">#</a><a id="UNTIE4"></a>UNTIE this </h2>

<p>You can define for all tie types an UNTIE method that will be called at untie(). See <a href="perltie.html#The-untie-Gotcha">&quot;The <code>untie</code> Gotcha&quot;</a> below.</p>

<h2 id="The-untie-Gotcha"><a class="permalink" href="perltie.html#The-untie-Gotcha">#</a><a id="The"></a>The <code>untie</code> Gotcha </h2>

<p>If you intend making use of the object returned from either tie() or tied(), and if the tie&#39;s target class defines a destructor, there is a subtle gotcha you <i>must</i> guard against.</p>

<p>As setup, consider this (admittedly rather contrived) example of a tie; all it does is use a file to keep a log of the values assigned to a scalar.</p>

<pre><code>package Remember;

use strict;
use warnings;
use IO::File;

sub TIESCALAR {
    my $class = shift;
    my $filename = shift;
    my $handle = IO::File-&gt;new( &quot;&gt; $filename&quot; )
                     or die &quot;Cannot open $filename: $!\n&quot;;

    print $handle &quot;The Start\n&quot;;
    bless {FH =&gt; $handle, Value =&gt; 0}, $class;
}

sub FETCH {
    my $self = shift;
    return $self-&gt;{Value};
}

sub STORE {
    my $self = shift;
    my $value = shift;
    my $handle = $self-&gt;{FH};
    print $handle &quot;$value\n&quot;;
    $self-&gt;{Value} = $value;
}

sub DESTROY {
    my $self = shift;
    my $handle = $self-&gt;{FH};
    print $handle &quot;The End\n&quot;;
    close $handle;
}

1;</code></pre>

<p>Here is an example that makes use of this tie:</p>

<pre><code>use strict;
use Remember;

my $fred;
tie $fred, &#39;Remember&#39;, &#39;myfile.txt&#39;;
$fred = 1;
$fred = 4;
$fred = 5;
untie $fred;
system &quot;cat myfile.txt&quot;;</code></pre>

<p>This is the output when it is executed:</p>

<pre><code class="plaintext">The Start
1
4
5
The End</code></pre>

<p>So far so good. Those of you who have been paying attention will have spotted that the tied object hasn&#39;t been used so far. So lets add an extra method to the Remember class to allow comments to be included in the file; say, something like this:</p>

<pre><code>sub comment {
    my $self = shift;
    my $text = shift;
    my $handle = $self-&gt;{FH};
    print $handle $text, &quot;\n&quot;;
}</code></pre>

<p>And here is the previous example modified to use the <code>comment</code> method (which requires the tied object):</p>

<pre><code>use strict;
use Remember;

my ($fred, $x);
$x = tie $fred, &#39;Remember&#39;, &#39;myfile.txt&#39;;
$fred = 1;
$fred = 4;
comment $x &quot;changing...&quot;;
$fred = 5;
untie $fred;
system &quot;cat myfile.txt&quot;;</code></pre>

<p>When this code is executed there is no output. Here&#39;s why:</p>

<p>When a variable is tied, it is associated with the object which is the return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This object normally has only one reference, namely, the implicit reference from the tied variable. When untie() is called, that reference is destroyed. Then, as in the first example above, the object&#39;s destructor (DESTROY) is called, which is normal for objects that have no more valid references; and thus the file is closed.</p>

<p>In the second example, however, we have stored another reference to the tied object in $x. That means that when untie() gets called there will still be a valid reference to the object in existence, so the destructor is not called at that time, and thus the file is not closed. The reason there is no output is because the file buffers have not been flushed to disk.</p>

<p>Now that you know what the problem is, what can you do to avoid it? Prior to the introduction of the optional UNTIE method the only way was the good old <code>-w</code> flag. Which will spot any instances where you call untie() and there are still valid references to the tied object. If the second script above this near the top <code>use warnings &#39;untie&#39;</code> or was run with the <code>-w</code> flag, Perl prints this warning message:</p>

<pre><code class="plaintext">untie attempted while 1 inner references still exist</code></pre>

<p>To get the script to work properly and silence the warning make sure there are no valid references to the tied object <i>before</i> untie() is called:</p>

<pre><code>undef $x;
untie $fred;</code></pre>

<p>Now that UNTIE exists the class designer can decide which parts of the class functionality are really associated with <code>untie</code> and which with the object being destroyed. What makes sense for a given class depends on whether the inner references are being kept so that non-tie-related methods can be called on the object. But in most cases it probably makes sense to move the functionality that would have been in DESTROY to the UNTIE method.</p>

<p>If the UNTIE method exists then the warning above does not occur. Instead the UNTIE method is passed the count of &quot;extra&quot; references and can issue its own warning if appropriate. e.g. to replicate the no UNTIE case this method can be used:</p>

<pre><code>sub UNTIE
{
 my ($obj,$count) = @_;
 carp &quot;untie attempted while $count inner references still exist&quot;
                                                             if $count;
}</code></pre>

<h1 id="SEE-ALSO"><a class="permalink" href="perltie.html#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1>

<p>See <a href="DB_File.html">DB_File</a> or <a href="Config.html">Config</a> for some interesting tie() implementations. A good starting point for many tie() implementations is with one of the modules <a href="./Tie::Scalar.html">Tie::Scalar</a>, <a href="./Tie::Array.html">Tie::Array</a>, <a href="./Tie::Hash.html">Tie::Hash</a>, or <a href="./Tie::Handle.html">Tie::Handle</a>.</p>

<h1 id="BUGS"><a class="permalink" href="perltie.html#BUGS">#</a>BUGS</h1>

<p>The normal return provided by <code>scalar(%hash)</code> is not available. What this means is that using %tied_hash in boolean context doesn&#39;t work right (currently this always tests false, regardless of whether the hash is empty or hash elements). [ This paragraph needs review in light of changes in 5.25 ]</p>

<p>Localizing tied arrays or hashes does not work. After exiting the scope the arrays or the hashes are not restored.</p>

<p>Counting the number of entries in a hash via <code>scalar(keys(%hash))</code> or <code>scalar(values(%hash)</code>) is inefficient since it needs to iterate through all the entries with FIRSTKEY/NEXTKEY.</p>

<p>Tied hash/array slices cause multiple FETCH/STORE pairs, there are no tie methods for slice operations.</p>

<p>You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file. The first problem is that all but GDBM and Berkeley DB have size limitations, but beyond that, you also have problems with how references are to be represented on disk. One module that does attempt to address this need is DBM::Deep. Check your nearest CPAN site as described in <a href="perlmodlib.html">perlmodlib</a> for source code. Note that despite its name, DBM::Deep does not use dbm. Another earlier attempt at solving the problem is MLDBM, which is also available on the CPAN, but which has some fairly serious limitations.</p>

<p>Tied filehandles are still incomplete. sysopen(), truncate(), flock(), fcntl(), stat() and -X can&#39;t currently be trapped.</p>

<h1 id="AUTHOR"><a class="permalink" href="perltie.html#AUTHOR">#</a>AUTHOR</h1>

<p>Tom Christiansen</p>

<p>TIEHANDLE by Sven Verdoolaege &lt;<i>skimo@dns.ufsia.ac.be</i>&gt; and Doug MacEachern &lt;<i>dougm@osf.org</i>&gt;</p>

<p>UNTIE by Nick Ing-Simmons &lt;<i>nick@ing-simmons.net</i>&gt;</p>

<p>SCALAR by Tassilo von Parseval &lt;<i>tassilo.von.parseval@rwth-aachen.de</i>&gt;</p>

<p>Tying Arrays by Casey West &lt;<i>casey@geeknest.com</i>&gt;</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
